/**
 * leeCalendar
 * version:1.0
 * author:lee
 * 1.使用示例：
     $(".xxx").Calendar({
            calendarData: scheduleData
        });
 *2.calendarData数据格式示例：
     var data = [
     {
         "scheduleDate":"2021-12-23",
         "domList":[{
              dom,dom,dom,dom...
          },...]
      },...];
 */
(function ($, window, document, undefined) {
    var leeCalendar = 'Calendar',
        defaults = {
            lastMonthEnable: true,//是否启用上个月的按钮
            nextMonthEnable: true,//是否启用下个月的按钮
            lastMonthCurrentEnable: true,//是否启用当前月份上个月
            nextMonthCurrentEnable: true,//是否启用当前月份下个月
            minWidth: 100,//列的最小宽度
            minHeight: 100,//列的最小高度
            calendarData: {},//自定义显示数据集
            monthChange:null
        };
    var Calendar = function (element, options) {
        this.elementObj = $(element);
        this.options = $.extend({}, defaults, options);//下拉选项
        this.dayTexts = [

            '星期一',
            '星期二',
            '星期三',
            '星期四',
            '星期五',
            '星期六',
            '星期日',
        ];
        this.showDate = new Date();
        this.init();
        this.initData();
    }
    Calendar.prototype = {
        init: function () {
            var _this = this;
            _this.elementObj.empty();
            var currentYear = _this.showDate.getFullYear();//当前年
            var currentMonthIndex = _this.showDate.getMonth();//当前月索引(0-11)
            _this.elementObj.append(_this.createCalendar(currentYear, currentMonthIndex));
        },
        createCalendar: function (year, monthIndex) {
            var _this = this;
            _this.getDateArgs(year, monthIndex);
            var calendarWrapper = $(' <div class="calendar-wrapper">');
            calendarWrapper.append(_this.createCalendarHead(year, monthIndex));
            calendarWrapper.append(_this.createCalendarMain(year, monthIndex));
            return calendarWrapper
        },
        createCalendarHead: function (year, monthIndex) {
            var _this = this;
            var calendarHead = $('<div class="calendar-head">');
            calendarHead.append('<div class="calendar-head-left">' + year + '年' + (monthIndex + 1) + '月</div>');
            var calendarHeadRight = $('<div class="calendar-head-right">');
            var lastBtn = $(' <a class="calendar-btn" href="javascript:;">上一个月</a>');
            var nextBtn = $(' <a class="calendar-btn" href="javascript:;">下一个月</a>');
            if (_this.options.lastMonthEnable) {
                var addLast = true;
                if (!_this.options.lastMonthCurrentEnable) {
                    if (new Date().getMonth() == monthIndex) {
                        addLast = false;
                    }
                }
                if (addLast) {
                    lastBtn.bind('click', function () {
                        _this.showLastMonth();
                    });
                    calendarHeadRight.append(lastBtn);
                }
            }

            if (_this.options.nextMonthEnable) {
                var addNext = true;
                if (!_this.options.nextMonthCurrentEnable) {
                    if (new Date().getMonth() == monthIndex) {
                        addNext = false;
                    }
                }
                if (addNext) {
                    nextBtn.bind('click', function () {
                        _this.showNextMonth();
                    });
                    calendarHeadRight.append(nextBtn);
                }
            }
            calendarHead.append(calendarHeadRight);
            return calendarHead;
        },
        showLastMonth: function () {
            this.showDate.setMonth(this.showDate.getMonth() - 1);
            this.init();
            this.btnCallBack();
        },
        showNextMonth: function () {
            this.showDate.setMonth(this.showDate.getMonth() + 1);
            this.init();
            this.btnCallBack();
        },
        btnCallBack:function(){
            if(this.options.monthChange != null ){
                if (typeof this.options.monthChange == "function") {
                    this.options.monthChange();
                }
            }
        },
        createCalendarMain: function (year, monthIndex) {
            var _this = this;
            var calendarMain = $('<div class="calendar-main">');
            var calendarTitle = $('<div class="calendar-title-box">');
            $.each(_this.dayTexts, function () {
                var calendarTitleColumn = $('<div class="calendar-title" >' + this + '</div>');
                calendarTitleColumn.css("min-width", _this.options.minWidth + 'px');
                calendarTitle.append(calendarTitleColumn);

            });
            calendarMain.append(calendarTitle);
            var calendarContent = $('<div class="calendar-content">');
            var today = new Date();
            $.each(_this.getDateArgs(year, monthIndex), function () {
                var calendarDate;
                if (this == 0) {
                    calendarDate = $('<div class="calendar-blank"></div>');
                } else {
                    calendarDate = $('<div class="calendar-date">' + this + '</div>');

                    if (today.getFullYear() == year && today.getMonth() == monthIndex && today.getDate() == this) {
                        calendarDate.addClass("calendar-today");
                    }
                    calendarDate.addClass("calendar-index-" + this);
                    calendarDate.append('<div class="calendar-schedule-box"></div>')
                }
                calendarDate.css("min-width", _this.options.minWidth + 'px');
                calendarDate.css("min-height", _this.options.minHeight + 'px');

                calendarContent.append(calendarDate);
            });
            calendarMain.append(calendarContent);
            return calendarMain;
        },
        getDateArgs: function (year, monthIndex) {
            var date = new Date(year, monthIndex, 1);
            var firstDay = date.getDay()-1;
            if(firstDay < 0) {
                firstDay = firstDay + 7;
            }
            var dateArgs = [];
            for (var i = 0; i < firstDay; i++) {
                dateArgs.push(0);
            }
            while (date.getMonth() == monthIndex) {
                dateArgs.push(date.getDate());
                date.setDate(date.getDate() + 1);
            }

            var replenish = 7 - dateArgs.length % 7;
            for (var i = 0; i < replenish; i++) {
                dateArgs.push(0);
            }
            return dateArgs;
        },
        initData: function () {
            var _this = this;

            _this.elementObj.find(".calendar-schedule-box").empty();
            $.each(_this.options.calendarData, function () {
                var __this = this;
                var schDate = parseStrToDate(__this.scheduleDate);
                if (schDate != null) {
                    if (_this.showDate.getFullYear() == schDate.getFullYear() && _this.showDate.getMonth() == schDate.getMonth()) {
                        var dateDom = _this.elementObj.find(".calendar-index-" + schDate.getDate()).find(".calendar-schedule-box");
                        $.each(__this.domList, function () {
                            dateDom.append(this);
                        })
                    }
                }
            });
        },setCalendarData:function (data) {
            this.options.calendarData = data;
        }
    };

    function parseStrToDate(strDate) {
        try {
            return new Date(Date.parse(strDate.replace(/-/g, "/")))
        } catch (e) {
            return null;
        }
    }


    $.fn[leeCalendar] = function (options) {
        var stArray = [];
        this.each(function () {
            if (!$.data(this, 'plugin_' + leeCalendar)) {
                $.data(this, 'plugin_' + leeCalendar, new Calendar(this, options));
                stArray.push($(this).data()['plugin_' + leeCalendar]);
            }
        });
        if (this.length === 1) {
            return stArray[0];
        } else {
            return stArray;
        }
    }

})(jQuery, window, document);